package filter;

import pojo.User;

import javax.servlet.*;
import javax.servlet.Filter;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {
    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest)request;
        HttpServletResponse resp=(HttpServletResponse)response;
        String[] urls = {"/login.jsp", "/register.jsp", "/css/","/images/","/js/", "/login", "/user", "/verifyCode"};
        String uri = req.getRequestURI();
        for (String u :urls){
            if (uri.contains(u)){
                chain.doFilter(req,resp);
                return;
            }
        }


        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("LOGIN_USER");
        if (user!=null){
            chain.doFilter(req,resp);
        }else {
            request.setAttribute("LOGIN_MSG","你尚未登录，请先登录！");
            req.getRequestDispatcher("/login.jsp").forward(req,resp);
            return;
        }
    }
}
